import { login, logout, getResource } from '@/api/user'
import {getToken, setToken, removeToken, setCookie, getCookie} from '@/utils/auth'
import { filterAsyncRouter, filterChildren } from '@/store/modules/permission'
import {constantRoutes, resetRouter} from '@/router'
import store from "@/store";
const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    resourceFlag: '',
    sidebarRouters: [],
    permissionRouters: []
  }
}

const assemblyResources = (rdata) => {
  const result = []
  //递归组装菜单树结构
  if (!rdata || rdata.length === 0) {
    // commit('SET_RESOURCE', "1")
    return [];
  }
  const tree = [];
  const map = {};

  // 第一步：将每个节点存储到 map 中，方便后续查找
  rdata.forEach(item => {
    map[item.id] = { ...item, children: [] };
  });

  const permissionRouters = [];
  // 第二步：遍历数据，构建树形结构
  rdata.forEach(item => {
    permissionRouters.push(item.path)
    const node = map[item.id];
    const parentId = item.pid;

    if (parentId === 0) {
      // 如果 pid 为 0，说明是根节点，直接添加到树中
      tree.push(node);
    } else {
      // 找到父节点，并将当前节点添加到父节点的 children 数组中
      const parentNode = map[parentId];
      if (parentNode) {
        parentNode.children.push(node);
      }
    }
  });
  const sidebarRoutes =  filterAsyncRouter(tree, false, true)
  sidebarRoutes.push({ path: '*', redirect: '/404', hidden: true })

  result[0] = sidebarRoutes
  result[1] = permissionRouters
  return result
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLE: (state, roleList) => {
    state.roleList = roleList
  },
  SET_RESOURCE: (state, resourceFlag) => {
    state.resourceFlag = resourceFlag
  },
  SET_SIDEBAR_ROUTERS: (state, routers) => {
    state.sidebarRouters = constantRoutes.concat(routers)
  },
  SET_PERMISSION_ROUTERS: (state, routers) => {
    state.permissionRouters = routers
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ account: username.trim(), password: password,cpCode: 'acbb',uuid:'111' }).then(response => {
        const { data } = response
        setCookie('LOGIN_INFO', data)
        commit('SET_TOKEN', data.tokenValue)
        setToken(data.tokenValue)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },
  // get user info
  getResource({ commit }) {
    return new Promise(resolve => {
      const loginInfo = JSON.parse(getCookie('LOGIN_INFO'))
      commit('SET_NAME', loginInfo.account)
      commit('SET_ROLE', loginInfo.roleList)
      commit('SET_AVATAR', loginInfo.avatar)
      //如果存在缓存，不请求后端
      if(getCookie("SET_SIDEBAR_ROUTERS") && getCookie("SET_SIDEBAR_ROUTERS").length > 0){
        const rdata = JSON.parse(getCookie("SET_SIDEBAR_ROUTERS"))
        commit('SET_RESOURCE', "1")
        const results = assemblyResources(rdata)
        const sidebarRoutes =  results[0]
        const permissionRouters =  results[1]
        commit('SET_SIDEBAR_ROUTERS',sidebarRoutes )
        commit('SET_PERMISSION_ROUTERS', permissionRouters)
        resolve(sidebarRoutes)
      }else{
        // 向后端请求路由数据
        getResource().then(res => {
          commit('SET_RESOURCE', "1")
          const rdata =  res.data
          const results = assemblyResources(rdata)
          const sidebarRoutes =  results[0]
          const permissionRouters =  results[1]
          commit('SET_SIDEBAR_ROUTERS',sidebarRoutes )
          commit('SET_PERMISSION_ROUTERS', permissionRouters)
          resolve(sidebarRoutes)
        })
      }
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove  token  first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit, state  }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  },
  GenerateRoutes({ commit }) {
    return new Promise(resolve => {
      // 向后端请求路由数据
      getResource().then(res => {
        const sdata = JSON.parse(JSON.stringify(res.data))
        const rdata = JSON.parse(JSON.stringify(res.data))
        const sidebarRoutes = filterAsyncRouter(sdata)
        const rewriteRoutes = filterAsyncRouter(rdata, false, true)
        rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true })
        commit('SET_ROUTES', rewriteRoutes)
        commit('SET_SIDEBAR_ROUTERS', sidebarRoutes)
        resolve(rewriteRoutes)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

